﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FruitCake.SimpleGallery.ViewModels
{
    public class SimpleGalleryPagerViewModel
    {
        public SimpleGalleryPagerViewModel(int itemCount, int pageIndex, int pageSize, int maxItems)
        {                        
            this.ItemCount = itemCount;
            this.PageIndex = pageIndex;
            this.PageSize = pageSize;

            if (maxItems < 1 || maxItems > PageCount) maxItems = PageCount;            
            
            int leftItems = maxItems / 2;
            int rightItems = maxItems - leftItems - 1;

            FirstItemIndex = 1;
            LastItemIndex = maxItems;

            if (pageIndex > leftItems)
            {
                FirstItemIndex = pageIndex - leftItems;

                if (FirstItemIndex < 1)
                {
                    FirstItemIndex = 1;
                    LastItemIndex = maxItems;
                }
                else
                {
                    LastItemIndex = FirstItemIndex + maxItems - 1;
                }

                if (LastItemIndex > PageCount)
                {
                    LastItemIndex = PageCount;
                    FirstItemIndex = PageCount - maxItems + 1;
                }
            }
        }

        public int ItemCount { get; private set; }
        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }

        public int PageItems
        {
            get
            {
                if (IsLastPage)
                    return ItemCount - (PageSize * (PageIndex - 1));
                else
                    return ItemCount < PageSize ? ItemCount : PageSize;
            }
        }

        public int PageCount
        {
            get
            {
                if (PageSize == 0) return 0;
                return (int)Math.Ceiling((double)ItemCount / PageSize);
            }
        }

        public bool IsFirstPage { get { return PageIndex == 1; } }
        public bool IsLastPage { get { return PageIndex == PageCount; } }

        public int FirstItemIndex { get; private set; }
        public int LastItemIndex { get; private set; }
    }
}